package com.stone.stoneanswer.controller;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.stone.stoneanswer.annotation.AuthCheck;
import com.stone.stoneanswer.common.BaseResponse;
import com.stone.stoneanswer.common.DeleteRequest;
import com.stone.stoneanswer.common.ErrorCode;
import com.stone.stoneanswer.common.ResultUtils;
import com.stone.stoneanswer.constant.UserConstant;
import com.stone.stoneanswer.exception.BusinessException;
import com.stone.stoneanswer.exception.ThrowUtils;
import com.stone.stoneanswer.model.dto.question.QuestionAddRequest;
import com.stone.stoneanswer.model.dto.question.QuestionAdminRequest;
import com.stone.stoneanswer.model.dto.question.QuestionGetRequest;
import com.stone.stoneanswer.model.dto.question.QuestionUpdateRequest;
import com.stone.stoneanswer.model.entity.QuestionOption;
import com.stone.stoneanswer.model.entity.Question;
import com.stone.stoneanswer.model.entity.User;
import com.stone.stoneanswer.model.vo.QuestionVO;
import com.stone.stoneanswer.service.QuestionService;
import com.stone.stoneanswer.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import com.stone.stoneanswer.model.vo.AnswerResultVO;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RestController
@RequestMapping("/question")
@Slf4j
public class QuestionController {

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 添加（仅管理员）
     *
     * @param
     * @param request
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addQuestion(@RequestBody QuestionAddRequest questionAddRequest, HttpServletRequest request) {
        if (questionAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 构造要插入的数据
        // 创建时间和修改时间使用的是数据库中的默认值，即当前时间
        Question question = new Question();
        BeanUtils.copyProperties(questionAddRequest, question);
        List<String> tags = questionAddRequest.getTags();
        List<QuestionOption> options = questionAddRequest.getOptions();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        if (options != null) {
            question.setOptions(JSONUtil.toJsonStr(options));
        }
        User loginUser = userService.getLoginUser(request);
        question.setUserId(loginUser.getId());
        question.setThumbNum(0);
        question.setFavourNum(0);

        // 插入数据
        boolean result = questionService.save(question);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        Long newId = question.getId();
        return ResultUtils.success(newId);
    }

    /**
     * 删除（仅管理员）
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> deleteQuestion(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || (deleteRequest.getId()==null && deleteRequest.getIds()==null) ){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = deleteRequest.getId();
        if(id!=null){
            // 判断是否存在
            Question oldQuestion = questionService.getById(id);
            ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);
            // 返回是否删除成功
            boolean result = questionService.removeById(id);
            return ResultUtils.success(result);
        }else{
            List<Long> ids = deleteRequest.getIds();
            boolean result = questionService.removeBatchByIds(ids);
            return ResultUtils.success(result);
        }
    }

    /**
     * 更新（仅管理员）
     */
    // TODO question表的options字段已经变更，需要更新代码
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateQuestion(@RequestBody QuestionUpdateRequest questionUpdateRequest) {
        // 参数校验
        if (questionUpdateRequest == null || questionUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        // 判断要更新的数据是否存在
        long id = questionUpdateRequest.getId();
        Question oldQuestion = questionService.getById(id);
        ThrowUtils.throwIf(oldQuestion == null, ErrorCode.NOT_FOUND_ERROR);

        // 构建更新用的对象
        Question question = new Question();
        BeanUtils.copyProperties(questionUpdateRequest, question);
        List<String> tags = questionUpdateRequest.getTags();
        if (tags != null) {
            question.setTags(JSONUtil.toJsonStr(tags));
        }
        List<QuestionOption> options = questionUpdateRequest.getOptions();
        if (options != null) {
            question.setOptions(JSONUtil.toJsonStr(options));
        }

        // 更新数据
        boolean result = questionService.updateById(question);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<QuestionVO> getQuestionVOById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Question question = questionService.getById(id);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionVO(question, request));
    }

    /**
     * 分页获取
     *
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<QuestionVO>> listQuestionVOByPage(@RequestBody QuestionGetRequest questionGetRequest,
                                                               HttpServletRequest request) {
        long current = questionGetRequest.getCurrent();
        long size = questionGetRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Question> questionPage = questionService.page(new Page<>(current, size),
                questionService.getQueryWrapper(questionGetRequest));
        //规范化返回值
        return ResultUtils.success(questionService.getQuestionVOPage(questionPage, request));
    }
    // endregion

    /**
     * 根据题库获取其中的题目
     */
    @PostMapping("/get/bankId")
    public BaseResponse<List<QuestionVO>> getQuestionByBankId(Long bankId) {
        if (bankId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionFromBank(bankId));
    }


    /**
     * 根据题库ID和题库类型获取题目信息
     * @param bankId
     * @param type
     * @return
     */
    @PostMapping("/get/bankId/type")
    public BaseResponse<List<QuestionVO>> getQuestionByBankIdAndType(Long bankId,Integer type) {
        if (bankId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtils.success(questionService.getQuestionFromBankByType(bankId , type));
    }

    @PostMapping("/admin")
    public BaseResponse<Boolean> adminQuestion(@RequestBody QuestionAdminRequest questionAdminRequest , HttpServletRequest request){
        DeleteRequest deleteRequest = questionAdminRequest.getDeleteRequest();
        List<QuestionUpdateRequest> updateRequest = questionAdminRequest.getUpdateRequest();
        List<QuestionAddRequest> addRequest = questionAdminRequest.getAddRequest();

        if(addRequest!=null&&!addRequest.isEmpty()){
            addRequest.forEach(questionAddRequest->{
                addQuestion(questionAddRequest , request);
            });
        }

        if(updateRequest!=null&&!updateRequest.isEmpty()){
            updateRequest.forEach(this::updateQuestion);
        }

        if(deleteRequest!=null&& !deleteRequest.getIds().isEmpty()){
            questionService.removeBatchByIds(deleteRequest.getIds());
        }
        return ResultUtils.success(true);
    }
}
